<?php

declare(strict_types=1);

namespace app\yperp\command;

use DateTime;
use Facebook\WebDriver\Exception\NoSuchWindowException;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Fastposter\Client as FastposterClient;
use think\console\Command;
use think\console\Input;

use think\console\Output;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Stream;
use GuzzleHttp\Psr7\Utils;
use InvalidArgumentException;
use RuntimeException;
use think\Db;
use think\facade\Cache;

class suosi3 extends Command
{

    protected $output;

    protected $input;
    protected $driver;
    protected $windows = [];
    protected $cookies = [];
    protected $token = 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2luZm8iOiIlN0IlMjJhdmF0YXIlMjIlM0ElMjJodHRwcyUzQSUyRiUyRndld29yay5xcGljLmNuJTJGd3dwaWMzYXolMkY5OTU3ODZfTnc0YXFZZEZTamFHbmpVXzE3MTYyNzc3MzMlMkYwJTIyJTJDJTIyY29ycElkJTIyJTNBJTIyd3cyYjFhOGVkZGIzMjcyZmZiJTIyJTJDJTIyaW5kdXN0cnlUeXBlJTIyJTNBJTIybXl0eGwlMjIlMkMlMjJsb2dpblR5cGUlMjIlM0ElMjJub3JtYWwlMjIlMkMlMjJtZW1iZXJJZCUyMiUzQTE3NjA5Mjg5MjA1MjY1ODAxMTMlMkMlMjJtZW1iZXJOYW1lJTIyJTNBJTIyJUU2JTlEJThFJUU0JUI4JTk2JUU1JUI5JUIzJTIyJTJDJTIybW9iaWxlJTIyJTNBJTIyMTg5ODExNDAxMDElMjIlMkMlMjJvcmdJZCUyMiUzQTEwMDAxMCUyQyUyMm9yZ05hbWUlMjIlM0ElMjIlRTklOTUlQkYlRTglOTklQjklRUYlQkMlODglRTYlOTklQkElRTYlOTglOTMlRTUlQUUlQjYlRUYlQkMlODklMjIlMkMlMjJvcmdUeXBlJTIyJTNBJTIyZ2VuZXJhbCUyMiUyQyUyMnJlZ2lvbkNvZGUlMjIlM0ElMjIwMDAwMDAwMDAwMDAwMDAwMDAlMjIlMkMlMjJzaG9ydE5hbWUlMjIlM0ElMjIlRTYlOTklQkElRTYlOTglOTMlRTUlQUUlQjYlMjIlMkMlMjJ1c2VySWQlMjIlM0ExNzYwOTI4OTIwNTI2NTgwMTEzJTJDJTIydXNlck5hbWUlMjIlM0ElMjIlRTYlOUQlOEUlRTQlQjglOTYlRTUlQjklQjMlMjIlMkMlMjJ1c2VyVHlwZSUyMiUzQSUyMmVtcGxveWVlJTIyJTdEIiwidXNlcl9uYW1lIjoiMTAwMDEwOzE3NjA5Mjg5MjA1MjY1ODAxMTM7ZW1wbG95ZWU7bm9ybWFsIiwib3JnX2lkIjoxMDAwMTAsInNjb3BlIjpbImFsbCJdLCJleHAiOjE3MjQzNzY1MzYsImp0aSI6IjBjZTlhNmQ3LWIwNDgtNDlmZS05YjkwLTljOWM3YzlhODNlNCIsImNsaWVudF9pZCI6InByb2R1Y3Rpb24ifQ.oELIeFt774ZgV-NDlJarV3uC4iOM9tyc7OVeL_cHUSL6eQpQP5Xxpqns_CWuBLfRaimxrR6PLw-YRb421HIxc71z5UoEXaLTjANN0ly4EMwLpbR6IYyg02w6cetYg4lSwM4K98j0QmW5u3K-L2_YK5LwJZAP-XfapfUBwSNrh6A';

    // 群活码分组id
    public $grpup_ids = [
        '1794922357957763073' => '芜湖',
        '1793135207802933249' => '合肥',
        '1784914950324916225' => '成都',
        '1784915354635022338' => '绵阳',
        '1772508002709778434' => '重庆',
        // '1763088628184178690' => '虹创',
    ];
    public $grpup_content_ids = [
        '空调中心' => '1787304428176216065',
        '冰洗中心' => '1787304368651841538',
        '电视中心' => '1787304312111435778',
    ];
    protected function configure()
    {
        // 指令配置
        $this->setName('suosi')
            ->setDescription('批量更新群标签');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $this->input = $input;

        $this->output = $output;
        try {

            $this->go();

        } catch (\Throwable $th) {
            dump($th->getMessage());
            dump($th->getTraceAsString());
        }
    }
    function go()
    {
        $datas = $this->get_group_list();
        foreach ($datas as $key => $data) {
            sleep(rand(1, 5));
            $tags = [];
            if (isset($this->grpup_ids[$data['groupId']])) {
                $type_name = $this->grpup_ids[$data['groupId']];

                dump($data['name']);
                $db = Db::table('dp_suosi_user1')->where(['dep' => $type_name, 'dep_name' => $data['name']])->find();

                // $grpup_content_ids = $this->grpup_content_ids[$db['dep_type'] . '中心'];
                dump(Db::getLastSql());
                // dump($db);
                if ($db) {
                    $tags[] = $this->search_group_tag($db['dep_type']);
                }

                $tags[] = $this->search_group_tag($type_name);

                $tags = array_filter($tags, function ($item) {
                    return count($item) > 0;
                });

                $groups = $this->search_group_name($data['roomBaseName']);
                if ($groups) {
                    $params = [
                        "id" => $groups['id'],
                        'groupLabelSignature' => $tags
                    ];
                    // dump(['go' => $params]);
                    dump(['save=>data'=>$params]);
                    $this->update_group_tag($params);
                }
                unset($tags);

            }

        }
    }
    function require($url = '', $body, $method = 'POST', $headers = [])
    {
        $client = new Client(['verify' => env('root_path') . 'application\yperp\common\cacert.pem',]);

        $headers['authorization'] = $this->token;
        $headers['content-type'] = 'application/json;charset=utf-8';

        $body = json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        dump($body);
        $request = new Request($method, $url, $headers, $body);
        $res = $client->sendAsync($request)->wait();
        $res = $res->getBody()->getContents();
        return json_decode($res, true);
    }
    public function update_group_tag($params)
    {
        $url = 'https://m.suosishequ.com/gateway/group/pc/internalGroupManager/updateLabel';
        $response = $this->require($url, $params);
        dump(['update_group_tag' => $response]);
    }

    public function get_group_list()
    {    //获取群活码列表
        $url = 'https://m.suosishequ.com/gateway/group/web/liveCode/group/findPageList';
        $response = $this->require($url, [
            "groupId" => '1794922357957763073', //合肥
            "search" => (object) [],
            // "search" => (object) ['keyword' => "四川星普五星电器德阳店"],
            "pageNo" => 1,
            "pageSize" => 500
        ]);
        // dump($response);
        return $response['data']['dataSource'];
    }

    public function search_group_tag($tag_name)
    {
        $url = 'https://m.suosishequ.com/gateway/user-center/select/component/search';
        $response = $this->require($url, [
            "keyword" => $tag_name,
            "types" => ["groupTagContacts"],
            "selectTypeList" => ["tag"],
            "noTagLabelPermission" => false,
            "tagTypeList" => [1]
        ]);
        dump(['search_group_tag' => $response]);
        // return $response['data']['dataSource'][0];
        if (!count($response['data']['dataSource'])) {
            return [];
        } else {

            return [
                "id" => $response['data']['dataSource'][0]['key'],
                "name" => $response['data']['dataSource'][0]['label'],
                "childDelete" => true,
                "labelPathName" => "分部",
                "type" => "GROUP_TAG",
                "key" => $response['data']['dataSource'][0]['key'],
                "orgId" => 100010,
                "contactType" => 14,
            ];
        }

    }
    public function search_group_name($group_name)
    {
        $url = 'https://m.suosishequ.com/gateway/group/pc/internalGroupManager/findPageList';
        $response = $this->require($url, [
            "search" => ["groupName" => "$group_name"],
            "pageNo" => 1,
            "pageSize" => 1,
        ]);
        dump(['search_group_name' => $response]);
        if (isset($response['data']['dataSource'][0])) {
            return $response['data']['dataSource'][0];
        }
        return false;
    }

    public function get_now_group_detail($group_id)
    {
        $url = 'https://m.suosishequ.com/gateway/group/pc/internalGroupManager/detail';
        $response = $this->require($url, [
            "id" => $group_id
        ], 'GET');

        dump(['get_now_group_detail' => $response]);
        return isset($response['data']['formValue']['groupLabelSignature']) ? true : false;
    }
}


